﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TransactionServer.General_Classes;
using System.Activities.Presentation.Model;
using System.Activities;

namespace TransactionServer.ActivityDesign.Components
{
    class DynamicEntityControl : ComboBox
    {

        public static readonly DependencyProperty ModelProperty =
       DependencyProperty.Register("Model", typeof(ModelItem), typeof(DynamicEntityControl),
       new FrameworkPropertyMetadata(
         null,
         FrameworkPropertyMetadataOptions.AffectsMeasure,
         new PropertyChangedCallback(UpdateList),
         null
     ));


        private List<string> VariableNames<T>()
        {
            List<string> variables = new List<string>();
            var mi = Model;

            while (mi.Parent != null)
            {
                Type parentType = mi.Parent.ItemType;
                if (typeof(Activity).IsAssignableFrom(parentType))
                {
                    // we have encountered an activity derived type
                    // look for variable collection
                    ModelProperty mp = mi.Parent.Properties["Variables"];
                    if (mp != null)
                    {
                        mp.Collection.ToList().ForEach(item =>
                            {
                                if (item.ItemType == typeof(Variable<T>) || item.ItemType == typeof(InArgument<T>))
                                {
                                    variables.Add(((Variable)item.GetCurrentValue()).Name);
                                }
                            });
                    }
                }
                mi = mi.Parent;
            }

            if (typeof(T) == typeof(Entity))
            {
                variables.Add("Evnt.Entity");
            }

            return variables;
        }

        public ModelItem Model
        {
            get
            {
                return (ModelItem)GetValue(ModelProperty);
            }
            set
            {
                SetValue(ModelProperty, value);
            }
        }

        public static void UpdateList(DependencyObject dObject, DependencyPropertyChangedEventArgs eventArgs)
        {
            var control = (DynamicEntityControl)dObject;

            if (control.Model != null)
            {
                control.ItemsSource = control.VariableNames<Entity>();
            }
            else
            {
                control.ItemsSource = null;
            }
        }

    }
}